import 'package:flutter/services.dart';

class NativeBridge {
  // 单例模式
  static final NativeBridge _instance = NativeBridge._internal();
  factory NativeBridge() => _instance;
  NativeBridge._internal();

  // 定义MethodChannel
  static const MethodChannel _channel =
      MethodChannel('samples.flutter.dev/battery');

  static const _eventChannel =
      EventChannel('samples.flutter.dev/event_channel');

  static const _basicChannel = BasicMessageChannel(
      "samples.flutter.dev/basic_channel", StandardMessageCodec());

  int count = 0;

  void init() {
    print('NativeBridge 初始化');
    // 初始化时可以添加监听事件等
    _eventChannel.receiveBroadcastStream().listen((event) {
      print('接收到事件: $event');
      // 处理事件
    }, onError: (error) {
      print('事件错误: $error');
    });
  }

  // 调用原生方法（带参数和返回值）
  Future<T?> invokeNativeMethod<T>(
    String methodName, [
    Map<String, dynamic>? arguments,
  ]) async {
    try {
      final result = await _channel.invokeMethod<T>(methodName, arguments);
      return result;
    } on PlatformException catch (e) {
      _handleError(e);
      return null;
    } on MissingPluginException {
      print('错误: 未找到原生实现');
      return null;
    } catch (e) {
      print('未知错误: $e');
      return null;
    }
  }

  // 自定义错误处理
  void _handleError(PlatformException e) {
    print('错误码: ${e.code}');
    print('错误信息: ${e.message}');
    print('错误详情: ${e.details}');

    // 可根据错误码进行不同处理
    switch (e.code) {
      case 'PERMISSION_DENIED':
        // 处理权限被拒绝的情况
        break;
      case 'INVALID_ARGUMENT':
        // 处理参数错误
        break;
      default:
      // 默认处理
    }
  }

  // 示例：获取电池电量
  Future<int?> getBatteryLevel() async {
    return await invokeNativeMethod<int>('getBatteryLevel');
  }

  Future<String?> testStreamCall() async {
    return await invokeNativeMethod<String>('callEvent');
  }

  Future<String?> testBasicChannel() async {
    String result;
    try {
      result = await _basicChannel.send(++count) as String;
    } on PlatformException catch (e) {
      result = "Error: $e";
    }
    return result;
  }

  // 示例：调用带参数的原生方法
  Future<String?> submitForm(Map<String, dynamic> formData) async {
    return await invokeNativeMethod<String>('submitForm', formData);
  }
}
